//
//  KKPopoverEditView.m
//  Butler
//
//  Created by liaozhenming on 16/6/20.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "KKPopoverAlertView.h"

@implementation KKPopoverAlertView

- (instancetype)init {
    return [self initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.7];
        
        _contentView = [[UIView alloc] initWithFrame: CGRectMake(200, 100, CGRectGetWidth(self.bounds) - 400, CGRectGetHeight(self.bounds) - 200)];
        _contentView.backgroundColor = [UIColor whiteColor];
        [_contentView kk_cornerRadius: 5.0];
        [self addSubview: _contentView];
        
        [self addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]];
    }
    return self;
}

- (void)kk_show {
    
    if (_isOpened) {
        return;
    }
    
    if (self.contentView == nil) {
        return;
    }
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview: self];
    
    self.alpha = CGFLOAT_MIN;
    self.contentView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    
    self.isOpened = YES;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration: 0.25 animations:^{
        weakSelf.alpha = 1.0;
        weakSelf.contentView.transform = CGAffineTransformIdentity;
    }completion:^(BOOL finished) {
        
    }];
}

- (void)kk_close {
    if (!_isOpened) {
        return;
    }
    
    if (self.contentView == nil) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration: 0.25 animations:^{
        weakSelf.alpha = CGFLOAT_MIN;
        weakSelf.contentView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    }completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
        weakSelf.isOpened = NO;
    }];
}

#pragma mark - 

- (void)onTap:(UITapGestureRecognizer *)tapper {
    CGPoint location = [tapper locationInView: _contentView];
    if (![_contentView pointInside: location withEvent: nil]) {
        [self kk_close];
    }
}

@end
